package me.zhengjie.modbusTCP;

import com.digitalpetri.modbus.master.ModbusTcpMaster;
import com.digitalpetri.modbus.master.ModbusTcpMasterConfig;
import com.digitalpetri.modbus.requests.ReadHoldingRegistersRequest;
import com.digitalpetri.modbus.responses.ReadHoldingRegistersResponse;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.config.NetConfig;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
@RequiredArgsConstructor
public class Disassembly1TCP {

    private final NetConfig netConfig;
    static ModbusTcpMaster master;

    /**
     * 获取TCP协议的Master
     */
//    @PostConstruct
    public void initModbusTcpMaster() {
        try {
            if (master == null) {
                // 创建配置
                ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder(netConfig.getDisassembly1Ip()).setPort(netConfig.getDisassembly1Port()).build();
                master = new ModbusTcpMaster(config);
                master.connect();
            }
        } catch (Exception e) {
            log.error("拆解1区plc连接失败，失败原因：{}",e.toString());
        }
    }

    public Integer readHoldingRegisters(int address){
        try {
            CompletableFuture<ReadHoldingRegistersResponse> future = master
                    .sendRequest(new ReadHoldingRegistersRequest(address, 1), 0);
            ReadHoldingRegistersResponse readHoldingRegistersResponse = future.get();

            if (readHoldingRegistersResponse != null) {
                ByteBuf buf = readHoldingRegistersResponse.getRegisters();
                int i = buf.readUnsignedShort();
                ReferenceCountUtil.release(readHoldingRegistersResponse);
                return i;
            }
            return null;
        } catch (Exception e) {
            log.error("拆解1区读取{}出错，错误原因：{}",address,e.toString());
            return null;
        }
    }
}
